package main

import (
	"encoding/json"
	"fmt"
	"gorm.io/gorm"
	"io"
	"net/http"
	"provider/config"
	"provider/model"
)

type User struct {
	gorm.Model
	Name  string
	Email string
}

func main() {

	http.HandleFunc("/db_supports", dbSupport)
	http.HandleFunc("/connect", connect)
	http.HandleFunc("/showDatabases", showDatabases)
	http.HandleFunc("/showTables", showTables)
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		fmt.Println("ListenAndServe: ", err)
		return
	}
}

func dbSupport(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		fmt.Println("this method is from GET  ")
	}
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write([]byte(`{"db_types":["mysql","postgresql","sqlite"]}`))
}

func showTables(w http.ResponseWriter, r *http.Request) {
	var bytes, _ = io.ReadAll(r.Body)
	var s = string(bytes)
	var ccc = config.DbConfig{}
	err := json.Unmarshal([]byte(s), &ccc)
	if err != nil {
		return
	}
	var db = config.DbInstanceMap[ccc.DbId]
	var c = db.Connect
	tabs := (*c).ShowTables()
	w.Header().Set("Content-Type", "application/json")
	result, _ := json.Marshal(tabs)
	w.Write(result)
}

func showDatabases(w http.ResponseWriter, r *http.Request) {
	var bytes, _ = io.ReadAll(r.Body)
	var s = string(bytes)
	var ccc = config.DbConfig{}
	err := json.Unmarshal([]byte(s), &ccc)
	if err != nil {
		return
	}
	var db = config.DbInstanceMap[ccc.DbId]
	var c = db.Connect
	dbs := (*c).ShowDatabase()
	w.Header().Set("Content-Type", "application/json")
	result, _ := json.Marshal(dbs)
	w.Write(result)
}

func connect(w http.ResponseWriter, r *http.Request) {
	var c = config.DbConfigFactory{
		R: r,
	}
	var mc = c.MakeConfig()
	var conn = mc.MakeConnInstance()
	conn.Connect()
	var cId = conn.DbInfo().DbId
	var data = model.Response{Data: model.ResponseData{ConnectId: cId}}
	res, _ := json.Marshal(data)
	w.Header().Set("Content-Type", "application/json")
	w.Write([]byte(res))
}
